<?php
namespace control;
// 固定资产登记
class assetManagementClass extends adIndexClass
{
    private const page = 'assetManagement'; # 权限
    private const table = 'asset_reg';       # 数据表
    private const title = '资产登记';
    private array $cardMethodOption = ['按数量拆分建卡', '不拆分建卡'];
    private array $depreciationMethod = ['不折旧', '直线折旧法', '双倍余额递减法'];

    /*固定资产入口页*/
    public function home(): string
    {
        $option['click'] = 'replaceContent(this, \'assetManagement\')';
        $all = self::getCatalogAll($option);
        //返回
        $rightHtml = $this->homeRight();
        $html = componentClass::leftNav([
            'title'=>'搜索分类',
            'click'=>$option['click'],
            'edit'=>1,
            'allTitle'=>'全部分类',
            'button'=>"<img class='tool-img' title='添加分类' onclick=\"layer('assetCatalog','edit',{id:'" . suiji() . "', pid: 0})\" src='".root."img/control/list_add.svg'>",
            'all'=>$all,
            'rightHtml'=>$rightHtml,
        ]);
        //返回
        return $this->homeFun($html);
    }

    /**
     * 左侧搜索框
     *
     * @return string
     */
    public function getContainerLeftJson(): string
    {
        $option['click'] = 'replaceContent(this, \'assetManagement\')';
        $json['html'] = self::getCatalogAll($option);
        return json_encode($json, 320);
    }

    public static function getCatalogAll($data = [])
    {
        $orderBy = ' ORDER BY list ASC ';
        // 条件
        $data['where'] = $data['where'] ?? "pid='0'";
        // 点击事件
        $data['click'] = $data['click'] ?? 'replaceDetail(this, \'assetCatalog\')';
        // 结果
        $result = find(['table' => 'asset_catalog', 'where' => $data['where'] . " and coid = '" . self::$coid . "'" . $orderBy]);
        $style = ($data['where'] == "pid='0'") ? '' : ' class="child-node"';
        $temp = "<ul {$style} {$data['where']}>";
        $textcontent_ico = "<span class='textcontent_ico'></span>";
        if ($result['array']) {
            foreach ($result['array'] as $value) {
                // 判断下级是否存在
                $data['where'] = " pid='{$value['id']}' ";
                $arrow = "<span class='arrow'  onclick=\"liZoom($(this).parent())\"></span>";
                $has = query('asset_catalog', $data['where'] . $orderBy);
                $dots = "<div class='actionBlock none'>
                            <img data-pid='{$value['id']}' title='添加子分组' onclick=\"layer('assetCatalog','edit',{pid:'{$value['id']}'})\" src='".root."img/control/list_add.svg'>
                            <img data-id='{$value['id']}' title='编辑' onclick=\"layer('assetCatalog','edit',{id:'" . $value['id'] . "'})\" src='".root."img/control/edit.svg'>
                            <img data-id='{$value['id']}' title='删除' onclick=\"layer('assetCatalog','operate',{'act': 'delType',id:'" . $value['id'] . "'})\" src='".root."img/control/list_del.svg'>
                        </div>";
                if ($has['id']) {
                    $temp .= "<li class='arrow-li' data-id='{$value['id']}' onclick=\"{$data['click']}\">
                                {$arrow}
                                <span class='textcontent'>{$textcontent_ico}{$value['name']}</span>
                                <div class='action-div'>{$dots}</div>
                            </li>";
                    $temp .= self::getCatalogAll($data);
                } else {
                    $temp .= "<li class='arrow-no-li' data-id='{$value['id']}' onclick=\"{$data['click']}\">
                                <span class='textcontent'>{$textcontent_ico}{$value['name']}</span>
                                <div class='action-div'>{$dots}</div>
                            </li>";
                }
            }
        }
        $temp .= '</ul>';
        return $temp;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编码" => text(array("name" => "orderNo")).
                        hidden(['name' => 'objId', 'value' => $this->post('objId')]),
                    "名称"   => text(array("name" => "name")),
                    "品牌"   => text(array("name" => "brand")),
                ],
                [
                    "规格型号"   => text(array("name" => "model")),
                    "登记日期" => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    public function homeRight(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "edit") && $this->post('objId')) {
            $root = $this->root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=editPage&id=' . self::getId() . '&acid=' . $this->post('objId');
            $button .= "
			<span class='spanButton' onclick=\"layer('".self::page."','editPage', {id: '".self::getId()."', acid: '".$this->post('objId')."'})\">新建</span>";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        }
        //返回
        return $this->search($html, layout: 'pop', toolButton: $button);
    }

    /**
     * 异步加载
     *
     */
    public function homeRightJson(): string
    {
        $json['html'] = $this->homeRight();
        return json_encode($json, 320);
    }

    public function homeRightJsonSearch(): string
    {
        return $this->homeSearch();
    }

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "单据编码",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => '名称',
                        'width' => 200,
                    ],
                    'brand'         => [
                        'name'  => '品牌',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 200,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 150,
                    ],
                    'num'          => [
                        'name'  => '数量',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'time'          => [
                        'name'  => '登记日期',
                        'width' => 150,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*固定资产列表*/
    public function homeSearch(): string
    {
        //全等查询数组
        $equal = [
            'acid' => $this->post('objId'),
            'coid' => self::$coid,
        ];
        $like = [
            'orderNo' => $this->post('orderNo'),
            'name' => $this->post('name'),
            'brand' => $this->post('brand'),
            'model' => $this->post('model'),
        ];
        //生成查询语句
        $where = search([
            "=" => $equal,
            "like" => $like,
        ]);
        if ($this->post('time')) {
            $where .= self::timeComparison($this->post('time'));
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => ["name" => "listId", "value" => $array['id']],
                "detail" => ["title" => "固定资产详情", "click" => "newIframe('固定资产详情','" . root . "control/adIndex.html?cla=assetManagement&fun=detail&id=" . $array['id'] . "')"],
                'preview' => ["title" => "固定资产详情", "click" => "newIframe('固定资产详情','" . root . "control/adIndex.html?cla=assetCenterClass&fun=detail&id=" . $array['id'] . "')"],
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'time':
                        $row[] = self::formatDate($array['time']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(num),0) as num",
        ]);
        $total    = [
            'num'        => $totalQuery['num'],
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        $json['html'] .= <<<efo
<script>

//分类下拉菜单页面
$(".dots").click(function(event) {
    $(".stateBlock").hide();
    let obj = $(this).find(".stateBlock");
      let state = obj.css('display');
    if (state == 'block') {
        obj.hide();
    } else {
        obj.show();
    }
　　　event.stopPropagation()
})
 //点击非下拉区域隐藏
$(document).bind('click', function (e) {
    let target = $(".stateBlock");
    if(!target.is(e.target) && target.has(e.target).length ===0){
      clearDiv();
    }
});
 function clearDiv(){
      $(".stateBlock").hide();
 }
</script>
efo;
        return json_encode($json, 320);
    }


    public function editPage(): string
    {
        $info = query(self::table, " id = '" . $this->post('id') . "' ");
        if (empty($this->post('acid')) && empty($info['id'])) {
            return json_encode(['warn'=>'请先选择分类'],320);
        }
        $acid = $info['acid'] ?: $this->post('acid');
        $staffArr = componentClass::departmentToStaff($info['departmentId']);
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    '分类' => assetCatalogClass::getCatalogName($acid) . hidden(['name' => "acid", 'class' => 'text', 'value' => $acid]),
                ],
                [
                    must . '名称' => text(['name' => "name", 'class' => 'text', 'value' => $info['name']]),
                    '品牌' => text(['name' => "brand", 'class' => 'text', 'value' => $info['brand']]),
                ],
                [
                    '规格型号' => text(['name' => "model", 'class' => 'text', 'value' => $info['model']]),
                    must . '计量单位' => select(['name' => "unit", 'class' => 'text', 'value' => $info['unit'], 'option' => para('unitOfMeasureOption', '，')]),
                ],
                [
                    must . '数量' => text(['name' => "num", 'type' => 'number', 'class' => 'text', 'value' => $info['num']]),
                    must . '建卡方式' => radio(['name' => "cardMethod", 'value' => $this->cardMethodOption, 'checked' => $info['cardMethod'] ?: $this->cardMethodOption[0]]),
                ],
                [
                    must . '附件清单' => text(['name' => "fileList", 'class' => 'text', 'value' => $info['fileList']]),
                    must . '开始使用日期' => text(['name' => "purchaseDate", 'class' => 'text', 'value' => $info['purchaseDate']?:$this->date, 'laydate' => []]),
                ],
                [
                    must . '资产原值' => text(['name' => "purchaseMoney", 'type' => 'number', 'class' => 'text', 'value' => $info['purchaseMoney'], 'unit' =>  static::$unit ]),
                    '预计净残值' => text(['name' => "money", 'type' => 'number', 'class' => 'text', 'value' => $info['money'], 'unit' =>  static::$unit ]),
                ],
                [
                    '累计折旧' => text(['name' => "depreciationMoney", 'type' => 'number', 'class' => 'text', 'value' => $info['depreciationMoney'], 'unit' =>  static::$unit ]),
                    '折旧年限' => text(['name' => "discountYear", 'class' => 'text', 'type' => 'number', 'value' => $info['discountYear'], 'unit' => '月']),
                ],
                [
                    must . '折旧方式' => select(['name' => "depreciationMethod", 'title' => '请选择', 'option' => $this->depreciationMethod, 'value' => $info['depreciationMethod'] ?: $this->depreciationMethod[0]]),
                    must . '闲置资产' => radio(['name' => "unused", 'value' => ['是', '否'], 'checked' => $info['unused'] ?: '是']),
                ],
                [
                    '使用部门' => selectMultiple([
                        "name" => "departmentId",
                        "title" => "请选择",
                        'value' => $info['departmentId'],
                        'table' => 'department',
                        'where' => " 1=1 order by time,list asc",
                        'sqlId' => 'id',
                        'sqlField' => 'name',
                        'change' => 'getStaff'
                    ]),
                    '使用人' => "<div id='pickId' style='width: 100%'>" . selectMultiple([
                            "name" => "useId",
                            "title" => "请选择",
                            'value' => $info['useId'],
                            'table' => 'staff',
                            'where' => "state !='离职' and stid In ('" . implode("','", $staffArr) . "')",
                            'sqlId' => 'stid',
                            'sqlField' => 'name'
                        ]) . "</div>",
                ],
                [
                    must . '保管部门' => selectMultiple([
                        "name" => "keepDeptId",
                        "title" => "请选择",
                        'value' => $info['keepDeptId'],
                        'table' => 'department',
                        'where' => " 1=1 order by time,list asc",
                        'sqlId' => 'id',
                        'sqlField' => 'name',
                    ]),
                    must . '存放地点' => text(['name' => "storage", 'class' => 'text', 'value' => $info['storage']]),
                ],
                [
                    '费用科目' => componentClass::subjectComponent(['name' => 'feeSubjectId', 'value'=>$info['feeSubjectId'],'inputName' => 'feeSubjectName', 'isShowParent' => false]),
                    '折旧科目' => componentClass::subjectComponent(['name' => 'disSubjectId', 'value'=>$info['disSubjectId'],'inputName' => 'disSubjectName', 'isShowParent' => false]),
                ],
                [
                    '备注' => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]) . hidden(['name' => 'id', 'value' => $info['id'] ?: $this->post('id')]),
                ],
            ],
        ]);
        $html .= <<<eof
<script>
function getStaff(e){
      $.post(root+'control/adIndex.html?cla=assetUse&fun=getStaff',{departmentId:e.value},function(res) {
          $("#pickId").html(res.html);
      },'json');
}
</script>
eof;
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 600, "html" => $html));
    }

    /*基本资料新增或修改-异步处理*/
    public function editPageEdit(): string
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'keepDeptId'=>$this->post('keepDeptId'),
            'acid' => $this->post('acid'),
            'name' => $this->post('name'),
            'brand' => $this->post('brand'),
            'model' => $this->post('model'),
            'unit' => $this->post('unit'),
            'purchaseDate' => $this->post('purchaseDate'),
            'purchaseMoney' => $this->post('purchaseMoney'),
            'money' => $this->post('money'),
            'num' => $this->post('num'),
            'discountYear' => $this->post('discountYear'),
            'storage' => $this->post('storage'),
            'useId' => $this->post('useId'),
            'departmentId' => $this->post('departmentId'),
            'text' => $this->post('text'),
            'cardMethod' => $this->post('cardMethod'),
            'fileList' => $this->post('fileList'),
            'depreciationMoney' => $this->post('depreciationMoney'),
            'depreciationMethod' => $this->post('depreciationMethod'),
            'unused' => $this->post('unused'),
            'feeSubjectId' => $this->post('feeSubjectId'),
            'disSubjectId' => $this->post('disSubjectId'),
        ];
        $annotation = [
            'acid' => '分类',
            'name' => '名称',
            'brand' => '品牌',
            'model' => '规格型号',
            'unit' => '计量单位',
            'cardMethod' => '建卡方式',
            'purchaseDate' => '开始使用日期',
            'purchaseMoney' => '资产原值(' . static::$unit . ')',
            'money' => '预计净残值',
            'num' => '数量',
            'depreciationMethod' => '折旧方式',
            'unused' => '闲置资产',
            'depreciationMoney' => '累计折旧',
            'fileList' => '附件清单',
            'discountYear' => '折价年限（月）',
            'storage' => '存放地点',
            'useId' => '使用人',
            'keepDeptId'=>'保管部门',
            'text' => '备注',
        ];
        $rules = [
            'acid' => 'required',
            'name' => 'required',
            'cardMethod' => 'required',
            'fileList' => 'required',
            'unit' => 'required',
            'purchaseDate' => 'required|date',
            'purchaseMoney' => 'required|numeric',
            'num' => 'required|numeric',
            'depreciationMethod' => 'required',
            'keepDeptId'=>'required',
            'storage' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif ($field['unused'] == '否' && empty($field['departmentId'])) {
            $json['warn'] = '请选择使用部门';
        }elseif(!empty($field['disSubjectId']) && !empty($field['feeSubjectId'])&&$field['disSubjectId'] == $field['feeSubjectId']){
            $json['warn'] = '费用科目和折旧科目不能相同';
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (sqlNum(self::table, " name = '{$field['name']}' AND brand = '{$field['brand']}'  AND model = '{$field['model']}' AND purchaseDate = '{$field['purchaseDate']}' AND id <> '$id'   ") > 0) {
                $json['warn'] = "资产「{$field['name']} - {$field['model']}」重复";
                goto resp;
            }
            if ($field['unused'] == '是') {
                $field['useId'] = '';
                $field['departmentId'] = '';
            }
            if (!$info['id']) {
                $orderNo = codeTemplateClass::generateCode(self::page, [
                    'table' => self::table,
                    'prefix' => 'YMRK' . date('Ymd'),
                    'default' => '001',
                ], $field);
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $orderNo,
                    'state' => '制单',
                    'coid' => self::$coid,
                    'stid' => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】' . (!empty($field['title']) ? "，标题【{$field['title']}】" : '');
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    public function detail(): string
    {
        $info = query(self::table, " id = '" . $this->get('id') . "' ");
        if (!$this->power(self::page, "see")) {
            $html = "你没有查看权限";
        } elseif (!$this->get('id')) {
            $html = "ID为空";
        } elseif (!$info['id']) {
            $html = "未找到此信息";
        } else {
            $data = [
                "id" => $info['id'],
            ];
            //按钮
            $button = [];

            if ($this->power(self::page, "edit") && $info['state'] == '制单') {
                $button[] = [
                    "name" => "确认",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
                $button[] = [
                    "name" => "编辑",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "editPage",
                    "post" => ["id" => $info['id']],
                ];
            }
            if ($this->power(self::page, "del")) {
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow([
                "基本信息" => [
                    [
                        "分类" => assetCatalogClass::getCatalogName($info['acid']),
                        "名称" => $info['name'],
                        "品牌" => $info['brand'],
                        "规格型号" => $info['model'],
                    ],
                    [
                        "单位" => $info['unit'],
                        "数量" => $info['num'],
                        "建卡方式" => $info['cardMethod'],
                        "附件清单" => $info['fileList'],
                    ],
                    [
                        "开始使用日期" => $info['purchaseDate'],
                        "资产原值(". static::$unit . ")" => self::formateNumber($info['purchaseMoney']),
                        "预计净残值(". static::$unit . ")" => self::formateNumber($info['money']),
                        "累计折旧(". static::$unit . ")" => self::formateNumber($info['depreciationMoney']),
                    ],
                    [
                        "折旧年限(月)" => $info['discountYear'],
                        "折旧方式" => $info['depreciationMethod'],
                        "闲置资产" => $info['unused'],
                        "使用部门" => departmentClass::getTypeName($info['departmentId']),
                    ],
                    [
                        "使用人" => self::findStaff($info['useId']),
                        "存放地点" => $info['storage'],
                    ],
                    [
                        "备注" => pre($info['text']),
                    ],
                ],
                "系统信息" => [
                    [
                        "单据编码" => $info['orderNo'],
                        "登记人" => self::findStaff($info['stid']),
                        "登记时间" => self::formatDate($info['time']),
                    ],
                ],
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    // 操作中转
    public function operate(): string
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        $append = [];
        switch ($act) {
            case 'delType':
                $act = 'del';
                $msg = '删除分类';
                $title = self::page . 'TypeDelete';
                $function = 'deleteType';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
            case 'confirm':
                $act = 'edit';
                $msg = '确认' . self::title;
                $title = self::page . 'Confirm';
                $function = 'confirmFun';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'isDelete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
                'append' => $append,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除分类
     * @return bool|string
     */
    public function deleteType(): bool|string
    {
        $array = $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query('asset_catalog', " id = '$id' ");
                if (!$this->juageDel($id)) {
                    $warn = "删除失败：此分类或子分类下存在固定资产";
                } else {
                    //递归删除
                    $this->deleteAll($id);
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= "资产分类ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了资产分类，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "成功删除{$x}条分类，详情请查看日志";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    public function deleteAll($id)
    {
        $material_type = query('asset_catalog', "pid = '$id'");
        if ($material_type['id']) {
            $this->deleteAll($material_type['id']);
        }
        delete(array('table' => 'asset_catalog', 'where' => "id = '$id'"));
    }

    private function juageDel($id): bool
    {
        $bool = true;
        $material_type = query('asset_catalog', "pid = '$id'");
        if ($material_type['id']) {
            $bool = $this->juageDel($material_type['id']);
        }
        if (static::total(array('table' => self::table, 'where' => "acid = '$id'")) > 0) {
            return false;
        }
        return $bool;
    }

    /**
     * 获取某个分类下的所有分类
     */
    public static function catalogCollection($typeId): array
    {
        $result = [];
        if (empty($typeId)) {
            return $result;
        } else {
            $result[] = $typeId;
        }
        $asset_catalog = find(array('table' => 'asset_catalog', 'where' => "pid = '$typeId'"));
        foreach ($asset_catalog['array'] as $array) {
            $result = array_merge($result, self::catalogCollection($array['id']));
        }
        return $result;
    }

    /**
     * 修改状态
     *
     * @return string
     */
    public function confirmFun(): string
    {
        $id = $this->post('id');
        $act = 'edit';
        $json = [];
        if (!$this->power(self::page, $act)) {
            $json['warn'] = "你没有此权限的权限";
        } elseif (empty($id)) {
            $json['warn'] = "你一条记录都没有选择呢";
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if ($info['state'] != '制单') {
                $json['warn'] = '非制单状态，无法确认登记';
                goto resp;
            } else {
                if ($info['cardMethod'] == '按数量拆分建卡') {
                    $x = 0;
                    for ($i = 1; $i <= $info['num']; $i++) {
                        $orderNo = codeTemplateClass::generateCode('assetList', [
                            'table' => 'asset',
                            'prefix' => 'YMFA' . date('Ymd'),
                            'default' => '001',
                        ], []);
                        $cid = self::getNo();
                        $bool = static::insert([
                            'table' => 'asset',
                            'field' => [
                                'id' => $cid,
                                'orderNo' => $orderNo,
                                'coid' => self::$coid,
                                'state' => $info['unused'] == '否' ? '使用中' : '在库',
                                'stid' => self::$stid,
                                'acid' => $info['acid'],
                                'regId' => $info['id'],
                                'name' => $info['name'],
                                'brand' => $info['brand'],
                                'model' => $info['model'],
                                'unit' => $info['unit'],
                                'purchaseDate' => $info['purchaseDate'],
                                'purchaseMoney' => $info['purchaseMoney'],
                                'money' => $info['money'],
                                'num' => 1,
                                'discountYear' => $info['discountYear'],
                                'storage' => $info['storage'],
                                'user' => $info['useId'],
                                'fileList' => $info['fileList'],
                                'depreciationMoney' => $info['depreciationMoney'],
                                'depreciationMethod' => $info['depreciationMethod'],
                                'unused' => $info['unused'],
                                'departmentId' => $info['unused'] == '否' ?$info['departmentId']:$info['keepDeptId'],
                                'userDepartment' => $info['unused'] == '否' ?departmentClass::getTypeName($info['departmentId']):departmentClass::getTypeName($info['keepDeptId'])
                            ],
                        ]);
                        if ($bool == '新增成功') {
                            static::insert([
                                'table' => 'asset_revert',
                                'field' => [
                                    'id' => self::getNo(),
                                    'atid' => $cid,
                                    'coid' => self::$coid,
                                    'type' => '登记',
                                    'storage' => $info['storage'],
                                ],
                            ], false);

                            $x++;
                        }
                    }
                    if ($x != $info['num']) {
                        $json['warn'] = '确认失败';
                    } else {
                        static::update([
                            'table' => self::table,
                            'field' => [
                                'state' => '已确认',
                            ],
                            'where' => $where,
                        ]);

                        //判断是否不是闲置资产，不是则生成领用记录
                        if ($info['unused'] == '否') {
                            $this->creatAssetUse($info);
                        }

                        $text = "管理员{$this->control['name']}确认了一条" . self::title . "：ID【{$id}】" . (!empty($info['title']) ? "，标题【{$info['title']}】" : '') . '<br>';
                        $this->logText(["type" => self::page, "text" => $text]);
                        $_SESSION['warn'] = "确认了{$x}条" . self::title;

                    }
                } elseif ($info['cardMethod'] == '不拆分建卡') {
                    $orderNo = codeTemplateClass::generateCode('assetList', [
                        'table' => 'asset',
                        'prefix' => 'YMFA' . date('Ymd'),
                        'default' => '001',
                    ], []);

                    $cid = self::getNo();
                    $bool = static::insert([
                        'table' => 'asset',
                        'field' => [
                            'id' => $cid,
                            'orderNo' => $orderNo,
                            'coid' => self::$coid,
                            'state' => $info['unused'] == '否' ? '使用中' : '在库',
                            'stid' => self::$stid,
                            'acid' => $info['acid'],
                            'regId' => $info['id'],
                            'name' => $info['name'],
                            'brand' => $info['brand'],
                            'model' => $info['model'],
                            'unit' => $info['unit'],
                            'purchaseDate' => $info['purchaseDate'],
                            'purchaseMoney' => $info['purchaseMoney'],
                            'money' => $info['money'],
                            'num' => $info['num'],
                            'discountYear' => $info['discountYear'],
                            'storage' => $info['storage'],
                            'user' => $info['useId'],
                            'fileList' => $info['fileList'],
                            'depreciationMoney' => $info['depreciationMoney'],
                            'depreciationMethod' => $info['depreciationMethod'],
                            'unused' => $info['unused'],
                            'departmentId' => $info['unused'] == '否' ?$info['departmentId']:$info['keepDeptId'],
                            'userDepartment' => $info['unused'] == '否' ?departmentClass::getTypeName($info['departmentId']):departmentClass::getTypeName($info['keepDeptId'])
                        ],
                    ]);
                    if ($bool == '新增成功') {
                        //判断是否不是闲置资产，不是则生成领用记录
                        if ($info['unused'] == '否') {
                            $this->creatAssetUse($info);
                        }
                        static::insert([
                            'table' => 'asset_revert',
                            'field' => [
                                'id' => self::getNo(),
                                'atid' => $cid,
                                'coid' => self::$coid,
                                'type' => '登记',
                                'storage' => $info['storage'],
                            ],
                        ]);
                        static::update([
                            'table' => self::table,
                            'field' => [
                                'state' => '已确认',
                            ],
                            'where' => $where,
                        ]);
                        $text = "{$this->control['name']}确认了" . self::title . "：ID【{$id}】" . "，名称【{$info['name']}】" . '<br>';
                        $this->logText(["type" => self::page, "text" => $text]);
                        $_SESSION['warn'] = "确认成功";
                    }
                }
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
            }
        }

        resp:
        return json_encode($json, 320);
    }

    private function creatAssetUse($info)
    {
        $field = [
            'id' => suiji(),
            'coid' => self::$coid,
            'department' => departmentClass::getTypeName($info['departmentId']),
            'departmentId' => $info['departmentId'],
            'state' => '已通过',
            'stid' => $this->control['stid'],
            'receiver' => $info['useId'],
            'receivingDate' => $this->date,
            'text' => '登记确认自动生成',
        ];
        $orderNo = codeTemplateClass::generateCode('assetUse', [
            'table' => 'asset_use',
            'prefix' => 'FABO' . date('Ymd'),
            'default' => '001',
        ], []);
        $field['orderNo'] = $orderNo;
        static::insert(["table" => 'asset_use', "field" => $field]);
        $all = find(array('table' => 'asset', 'where' => "regId = '$info[id]'"));
        foreach ($all['array'] as $array) {
            static::insert([
                "table" => 'asset_use_detail',
                "field" => [
                    'id' => suiji(),
                    'orderId' => $field['id'],
                    'coid' => self::$coid,
                    'atid' => $array['id'],
                    'storage' => $array['storage'],
                    'num' => $array['num'],
                ],
            ]);
            static::insert([
                'table' => 'asset_revert',
                'field' => [
                    'id' => self::getNo(),
                    'coid' => self::$coid,
                    'atid' => $array['id'],
                    'userDepartment' => departmentClass::getTypeName($info['departmentId']),
                    'user' => $info['useId'],
                    'type' => '领用',
                    'storage' => $info['storage'],
                ],
            ]);
        }
    }


    // 确认删除信息
    public function isDelete(): string
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除" . self::title . "的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一条记录都没有选择呢";
        } else {
            $text = '';
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            // 判断field

            foreach ($array as $id) {
                $where = " id = '$id' ";
                $info = query(self::table, $where);
                if ($info['id']) {
                    if (static::total(array('table' => 'asset', 'where' => "regId = '$id' and state != '在库'")) > 0) {
                        $text .= self::title . "【{$info['id']}】存在使用的状态，无法删除<br>";
                        continue;
                    }
                    delete([
                        "table" => self::table,
                        "where" => $where,
                    ]);
                    delete([
                        "table" => 'asset',
                        "where" => "regId = '$id'",
                    ]);
                    //添加记录
                    $text .= "{$this->control['name']}删除了一条" . self::title . "：ID【{$id}】" . ($info['name'] ? "，名称【{$info['name']}】" : '') . '<br>';
                    $x++;
                }
            }

            // 写入日志
            $this->logText(["type" => self::page, "text" => $text]);
            $_SESSION['warn'] = "删除了{$x}条" . self::title;
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        }else {
            $exampleData[] = ['电子产品>电脑','华为MateBook','华为','mateBook-X','台','1','不拆分建卡','无','2022-01-01',8999,4999,0,36,'直线折旧法','否','DP0007','总经办','YM202112310005','小吴','总经办办公室','','','测试数据，导入请删除此条数据'];
            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '分类'=>$example[0],
                            '名称'=>$example[1],
                            '品牌'=>$example[2],
                            '规格型号'=>$example[3],
                            '计量单位'=>$example[4],
                            '数量'=>$example[5],
                            '建卡方式'=>$example[6],
                            '附件清单'=>$example[7],
                            '开始使用日期'=>$example[8],
                            '资产原值'=>$example[9],
                            '预计净残值'=>$example[10],
                            '累计折旧'=>$example[11],
                            '折价期限'=>$example[12],
                            '折旧方式'=>$example[13],
                            '闲置资产'=>$example[14],
                            '使用部门编号'=>$example[15],
                            '使用部门名称'=>$example[16],
                            '使用人编号'=>$example[17],
                            '使用人名称'=>$example[18],
                            '存放地点'=>$example[19],
                            '费用科目代码'=>$example[20],
                            '折旧科目代码'=>$example[21],
                            '备注'=>$example[22],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
            $text = $this->control['name'] . "下载了资产登记导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }
    /*数据导入分析*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑的权限';
        } else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $headArray = [];
            $row_list=0;
            $unitOption = para('unitOfMeasureOption', '，');
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    //多级分类分割
                    $typeArr = explode("&gt;", $cell['分类']);
                    if (is_array($typeArr)) {
                        $pid = '0';
                        foreach ($typeArr as $name) {
                            $type = query('asset_catalog', "name = '$name' and pid = '$pid' and coid = '" . self::$coid . "'");
                            if (empty($type['id'])) {
                                $typeField = [
                                    'id' => self::getId(),
                                    'coid' => self::$coid,
                                    'pid' => $pid ?: '0',
                                    "name" => $name,      //部门名称
                                    "list" => 0,      //排序号
                                ];
                                insert(array('table' => 'asset_catalog', "field" => $typeField));
                                $pid = $typeField['id'];
                                $type['id'] = $typeField['id'];
                            } else {
                                $pid = $type['id'];
                            }
                        }
                    }
                    $cell['开始使用日期'] = self::importDateFormat($cell['开始使用日期']);
                    $department = query('department', "orderNo = '$cell[使用部门编号]'");
                    $staff = query('staff', "orderNo = '$cell[使用人编号]' and state !='离职'");
                    $feeSubject = query('subject',"coid = '".self::$coid."' and code = '$cell[费用科目代码]'");
                    $disSubject = query('subject',"coid = '".self::$coid."' and code = '$cell[折旧科目代码]'");

                    $field = [
                        'acid' => $type['id'] ?? '',
                        'name' => $cell['名称'],
                        'brand' => $cell['品牌'],
                        'model' => $cell['规格型号'],
                        'unit' => $cell['计量单位'],
                        'purchaseDate' => $cell['开始使用日期'],
                        'purchaseMoney' => $cell['资产原值'],
                        'useId' => $staff['stid'],
                        'money' => $cell['预计净残值'],
                        'num' => $cell['数量'],
                        'discountYear' => $cell['折价期限'],
                        'storage' => $cell['存放地点'],
                        'departmentId' => $department['id'],
                        'text' => $cell['备注'],
                        'cardMethod' => $cell['建卡方式'],
                        'fileList' => $cell['附件清单'],
                        'depreciationMoney' => $cell['累计折旧'],
                        'depreciationMethod' => $cell['折旧方式'] ?: '不折旧',
                        'unused' => $cell['闲置资产'] ?: '是',
                        'feeSubjectId' =>$feeSubject['id'],
                        'disSubjectId' => $disSubject['id'],
                    ];
                    $annotation = [
                        'acid' => '分类',
                        'name' => '名称',
                        'brand' => '品牌',
                        'model' => '规格型号',
                        'unit' => '计量单位',
                        'cardMethod' => '建卡方式',
                        'purchaseDate' => '开始使用日期',
                        'purchaseMoney' => '资产原值(' . static::$unit . ')',
                        'money' => '预计净残值',
                        'num' => '数量',
                        'depreciationMethod' => '折旧方式',
                        'unused' => '闲置资产',
                        'depreciationMoney' => '累计折旧',
                        'fileList' => '附件清单',
                        'discountYear' => '折价年限（月）',
                        'storage' => '存放地点',
                        'useId' => '使用人',
                        'text' => '备注',
                    ];
                    $rules = [
                        'acid' => 'required',
                        'name' => 'required',
                        'cardMethod' => 'required',
                        'fileList' => 'required',
                        'unit' => 'required',
                        'purchaseDate' => 'required|date',
                        'purchaseMoney' => 'required|numeric',
                        'num' => 'required|numeric',
                        'depreciationMethod' => 'required',
                        'storage' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    if ($result === false) {
                        $text .= "第【{$row_list}】行：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                    } elseif (sqlNum(self::table, " name = '{$field['name']}' AND brand = '{$field['brand']}'  AND model = '{$field['model']}' AND purchaseDate = '{$field['purchaseDate']}'") > 0) {
                        $text .= "第【{$row_list}】行：已存在此资产<br>";
                    } elseif ($field['unused'] == '否' && empty($field['departmentId'])) {
                        $text .= "第【{$row_list}】行：未找到使用部门：闲置资产为否时使用部门必填<br>";
                    } elseif (!in_array($field['cardMethod'], $this->cardMethodOption)) {
                        $text .= "第【{$row_list}】行：建卡方式不在可选范围中<br>";
                    } elseif (!in_array($field['depreciationMethod'], $this->depreciationMethod)) {
                        $text .= "第【{$row_list}】行：折旧方式不在可选范围中<br>";
                    } elseif (!in_array($field['unused'], ['是', '否'])) {
                        $text .= "第【{$row_list}】行：闲置资产选项不在可选范围中<br>";
                    } elseif (!in_array($field['unit'], $unitOption)) {
                        $text .= "第【{$row_list}】行：计件单位不在可选范围中<br>";
                    }elseif(!empty($cell['费用科目代码']) && empty($field['feeSubjectId'])){
                        $text .= "第【{$row_list}】行：未找到费用科目<br>";
                    }elseif(!empty($cell['折旧科目代码']) && empty($field['disSubjectId'])){
                        $text .= "第【{$row_list}】行：未找到折旧科目<br>";
                    } elseif(!empty($field['disSubjectId']) && !empty($field['feeSubjectId'])&&$field['disSubjectId'] == $field['feeSubjectId']){
                        $text .= "第【{$row_list}】行：费用科目和折旧科目不能相同<br>";
                    }else {
                        if ($field['unused'] == '是') {
                            $field['useId'] = '';
                            $field['departmentId'] = '';
                        }
                        $orderNo = codeTemplateClass::generateCode(self::page, [
                            'table' => self::table,
                            'prefix' => 'YMRK' . date('Ymd'),
                            'default' => '001',
                        ], $field);
                        $field = array_merge($field, [
                            'id' => suiji(),
                            'orderNo' => $orderNo,
                            'state' => '制单',
                            'coid' => self::$coid,
                            'stid' => $this->control['stid'],
                        ]);
                        $warn = insert(["table" => self::table, "field" => $field]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= "第【{$row_list}】行：导入成功<br>";
                        } else {
                            $text .= "第【{$row_list}】行：导入失败：编辑失败<br>";
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $data = [];
            $sql = $_SESSION[self::page]['sql'];
            $title = ['单据编码', '分类', '名称', '品牌', '规格型号', '数量', '单位', '建卡方式', '附件清单', '开始使用日期', '资产原值(' . static::$unit . ')', '预计净残值(' . static::$unit . ')', '累计折旧(' . static::$unit . ')', '折旧年限(月)', '折旧方式', '闲置资产', '使用部门', '使用人', '存放地点', '备注', '登记人', '登记时间'];
            $result = self::sqlFind($sql);
            if (is_array($result)) {
                foreach ($result as $array) {
                    $type = assetCatalogClass::getCatalogName($array['acid']);
                    $data[] = [
                        $array['orderNo'],
                        $type,
                        $array['name'],
                        $array['brand'],
                        $array['model'],
                        $array['num'],
                        $array['unit'],
                        $array['cardMethod'],
                        $array['fileList'],
                        $array['purchaseDate'],
                        $array['purchaseMoney'],
                        $array['money'],
                        $array['depreciationMoney'],
                        $array['discountYear'],
                        $array['depreciationMethod'],
                        $array['unused'],
                        departmentClass::getTypeName($array['departmentId']),
                        self::findStaff($array['useId']),
                        $array['storage'],
                        $array['text'],
                        self::findStaff($array['stid']),
                        $array['time'],
                    ];
                }
            }
            $text = $this->control['name'] . "导出了资产登记";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "资产登记.xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }


    /**
     * 剩余净值
     */
    public static function calcRemindMoney(string $type, float $monthDecMoney, string $purchaseDate, $discountYear, $purchaseMoney, $remindMoney,$depreciationMoney, $endDate = null): float
    {
        switch ($type) {
            case '直线折旧法':
                if (!$endDate) {
                    $endDate = date('Y-m-d');
                }
                if (strtotime($endDate) < strtotime($purchaseDate)) {
                    $endDate = $purchaseDate;
                }
                $month = self::getMonthNum($purchaseDate, $endDate);
                if ($month > $discountYear) {
                    return $remindMoney;
                }
                // 当前残值=购置金额-购置金额/折价期限*（MONTH（当前日期-购置日期）+1）
                $money = $purchaseMoney-$depreciationMoney-$month * $monthDecMoney;
                break;
            case '双倍余额递减法':
                if (!$endDate) {
                    $endDate = date('Y-m-d');
                }
                if (strtotime($endDate) < strtotime($purchaseDate)) {
                    $endDate = $purchaseDate;
                }
                $month = self::getMonthNum($purchaseDate, $endDate);
                if ($month > $discountYear) {
                    return $remindMoney;
                }
                $result = self::judgeExceed($discountYear, $purchaseMoney, $remindMoney);
                if ($result !== false && $month > ($discountYear - $result * 12)) {
                    $money = self::calcSalvage('直线折旧法', $monthDecMoney, $purchaseDate, $discountYear, $purchaseMoney, $remindMoney,$depreciationMoney, $endDate);
                } else {
                    $decMoney = 0;
                    for ($i = 1; $i <= ceil($month / 12); $i++) {
                        $decMoney += $purchaseMoney * pow(1 - (2 / ceil($discountYear / 12)), $i - 1) * 2 / ceil($discountYear / 12);
                    }

                    $floorMonth = ceil($month / 12) * 12 - $month;
                    $floorMonthMoney = $purchaseMoney * pow(1 - (2 / ceil($discountYear / 12)), ceil($month / 12) - 1) * 2 / ceil($discountYear / 12) / 12;
                    $decMoney -= $floorMonthMoney * $floorMonth;
                    $money = $purchaseMoney-$decMoney;
                }
                break;
            default:
                $money = $purchaseMoney;
                break;
        }
        return round($money, 2);
    }

    /**
     * 累计折旧
     *
     * @param string $type 折旧方式
     * @param float $monthDecMoney
     * @param string $purchaseDate 开始使用日期
     * @param $discountYear
     * @param $purchaseMoney
     * @param $remindMoney
     * @param $depreciationMoney
     * @param null $endDate
     * @return float
     */
    public static function calcSalvage(string $type, float $monthDecMoney, string $purchaseDate, $discountYear, $purchaseMoney, $remindMoney, $depreciationMoney,$endDate = null): float
    {
        switch ($type) {
            case '直线折旧法':
                if (!$endDate) {
                    $endDate = date('Y-m-d');
                }
                if (strtotime($endDate) < strtotime($purchaseDate)) {
                    $endDate = $purchaseDate;
                }
                $month = self::getMonthNum($purchaseDate, $endDate);
                if ($month > $discountYear) {
                    return $remindMoney;
                }
                $setting = optionSettingClass::getSetting('总账');
                $setting['depreciation']=$setting['depreciation']??0;
                if ($month == $discountYear && $setting['depreciation']){
                    $disMoney = $monthDecMoney*($discountYear-1);
                    $lastDisMoney = round($purchaseMoney-$depreciationMoney-$remindMoney-$disMoney,2);
                    $money = $monthDecMoney*($discountYear-1)+$lastDisMoney;
                }else{
                    // 当前残值=购置金额-购置金额/折价期限*（MONTH（当前日期-购置日期）+1）
                    $money = $month * $monthDecMoney;
                }

                break;
            case '双倍余额递减法':
                if (!$endDate) {
                    $endDate = date('Y-m-d');
                }
                if (strtotime($endDate) < strtotime($purchaseDate)) {
                    $endDate = $purchaseDate;
                }
                $month = self::getMonthNum($purchaseDate, $endDate);
                if ($month > $discountYear) {
                    return $remindMoney;
                }
                $result = self::judgeExceed($discountYear, $purchaseMoney, $remindMoney);
                if ($result !== false && $month > ($discountYear - $result * 12)) {

                    $money = self::calcSalvage('直线折旧法', $monthDecMoney, $purchaseDate, $discountYear, $purchaseMoney, $remindMoney,$depreciationMoney, $endDate);
                } else {
                    $decMoney = 0;
                    for ($i = 1; $i <= ceil($month / 12); $i++) {
                        $decMoney += $purchaseMoney * pow(1 - (2 / ceil($discountYear / 12)), $i - 1) * 2 / ceil($discountYear / 12);
                    }

                    $floorMonth = ceil($month / 12) * 12 - $month;
                    $floorMonthMoney = ceil($discountYear / 12)==0?
                        0:
                        $purchaseMoney * pow(1 - (2 / ceil($discountYear / 12)), ceil($month / 12) - 1) * 2 / ceil($discountYear / 12) / 12;
                    $decMoney -= $floorMonthMoney * $floorMonth;
                    $money = $decMoney;
                }
                break;
            default:
                $money = 0;
                break;
        }
        return round($money, 2);
    }


    /**
     * 获取两个日期间的月份数
     * @param $date1
     * @param $date2
     * @return int
     */
    public static function getMonthNum($date1, $date2): int
    {
        $date1 = date("Y-m-d", strtotime($date1));
        $date2 = date("Y-m-d", strtotime($date2));
        if (strtotime($date1) > strtotime($date2)) {
            $tmp = $date2;
            $date2 = $date1;
            $date1 = $tmp;
        }
        list($Y1, $m1, $d1) = explode('-', $date1);
        list($Y2, $m2, $d2) = explode('-', $date2);
        $y = $Y2 - $Y1;
        $m = $m2 - $m1;
        $d = $d2 - $d1;
        if ($d < 0) {
            $m--;
        }
        if ($m < 0) {
            $m += 12;
            $y--;
        }
        return $y * 12 + $m;
    }

    /**
     *
     *
     * 月折旧额
     * @param string $type 折旧方式
     * @param float $purchaseMoney
     * @param $ratio
     * @param $purchaseDate
     * @param $endDate
     * @param $discountYear
     * @param $remindMoney
     * @param $depreciationMoney
     * @return float
     */
    public static function monthDecMoney(string $type, float $purchaseMoney, $ratio, $purchaseDate, $endDate, $discountYear, $remindMoney, $depreciationMoney): float
    {
        if (!$endDate) {
            $endDate = date('Y-m-d');
        }
        if (strtotime($endDate) < strtotime($purchaseDate)) {
            $endDate = $purchaseDate;
        }
        $month = self::getMonthNum($purchaseDate, $endDate);
        if ($month > $discountYear) {
            return 0;
        }
        switch ($type) {
            case '直线折旧法':
                $setting = optionSettingClass::getSetting('总账');
                $setting['depreciation']=$setting['depreciation']??0;
                if ($month == $discountYear && $setting['depreciation']){
                    $disMoney = round($purchaseMoney * $ratio,2)*($discountYear-1);
                    $money = round($purchaseMoney-$depreciationMoney-$remindMoney-$disMoney,2);
                }else{
                    $money = ($purchaseMoney-$depreciationMoney) * $ratio;
                }

                break;
            case '双倍余额递减法':
                $result = self::judgeExceed($discountYear, $purchaseMoney, $remindMoney);
                if ($result !== false && $month > ($discountYear - $result * 12)) {
                    $money = self::monthDecMoney('直线折旧法', $purchaseMoney, $ratio, $purchaseDate, $endDate, $discountYear, $remindMoney, $depreciationMoney);
                } else {
                    $decMoney = $discountYear>0?($purchaseMoney * pow(1 - (2 / ceil($discountYear / 12)), ceil($month / 12) - 1) * 2 / ceil($discountYear / 12)):0;
                    $money = $decMoney / 12;
                }
                break;
            default:
                $money = 0;
                break;
        }
        return round($money, 2);
    }

    /**
     * 月折旧率
     */
    public static function monthRatio($type, $discountYear, $remindMoney, $purchaseMoney, $depreciationMoney, $purchaseDate, $endDate, $isPercent = 0): float|int
    {
        if (!$endDate) {
            $endDate = date('Y-m-d');
        }
        if (strtotime($endDate) < strtotime($purchaseDate)) {
            $endDate = $purchaseDate;
        }
        $month = self::getMonthNum($purchaseDate, $endDate);
        if ($month > $discountYear) {
            return 0;
        }
        switch ($type) {
            case '直线折旧法':
                if ($purchaseMoney > 0 && $discountYear > 0 && $purchaseMoney != $depreciationMoney) {
                    $ratio =$discountYear>0? (1 - $remindMoney / ($purchaseMoney - $depreciationMoney)) / $discountYear :0;
                } else {
                    $ratio = 0;
                }
                break;
            case '双倍余额递减法':

                $result = self::judgeExceed($discountYear, $purchaseMoney, $remindMoney);
                if ($result !== false && $month > ($discountYear - $result * 12)) {
                    $ratio = self::monthRatio('直线折旧法', $discountYear, $remindMoney, $purchaseMoney, $depreciationMoney, $purchaseDate, $endDate);
                } else {
                    $ratio = $discountYear > 0 ? 2 / $discountYear : 0;
                }
                break;
            default:
                $ratio = 0;
                break;
        }
        $setting = optionSettingClass::getSetting('总账');
        $depreciationrate = $setting['depreciationrate']??2;
        $depreciationrate = (int)$depreciationrate+2;
        return $isPercent ? round($ratio, $depreciationrate) * 100 : round($ratio, $depreciationrate);
    }

    /**
     * 双倍余额递减法
     * 判断是否超过了预计剩余净值
     */
    public static function judgeExceed($discountYear, $purchaseMoney, $remindMoney): bool|int
    {
        if ($discountYear == 0 || $purchaseMoney == 0) {
            return false;
        }
        $decMoney = 0;
        for ($i = 1; $i <= ceil($discountYear / 12); $i++) {
            $decMoney += $purchaseMoney * pow(1 - (2 / ceil($discountYear / 12)), $i - 1) * 2 / ceil($discountYear / 12);
            if ($decMoney > $remindMoney) {
                return $i - 1;
            }
        }
        return false;
    }

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'分类',
                    'aliasName'=>'分类(多级用>分开)',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'名称',
                    'aliasName'=>'名称',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'品牌',
                    'aliasName'=>'品牌',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'计量单位',
                    'aliasName'=>'计量单位',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'数量',
                    'aliasName'=>'数量',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'建卡方式',
                    'aliasName'=>'建卡方式',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'附件清单',
                    'aliasName'=>'附件清单',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'开始使用日期',
                    'aliasName'=>'开始使用日期',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'资产原值',
                    'aliasName'=>'资产原值',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'预计净残值',
                    'aliasName'=>'预计净残值',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'累计折旧',
                    'aliasName'=>'累计折旧',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'折价期限',
                    'aliasName'=>'折价期限（月）',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'折旧方式',
                    'aliasName'=>'折旧方式',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'闲置资产',
                    'aliasName'=>'闲置资产(是/否)',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'使用部门编号',
                    'aliasName'=>'使用部门编号',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'使用部门名称',
                    'aliasName'=>'使用部门名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'使用人编号',
                    'aliasName'=>'使用人编号',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'使用人名称',
                    'aliasName'=>'使用人名称',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'存放地点',
                    'aliasName'=>'存放地点',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'费用科目代码',
                    'aliasName'=>'费用科目代码',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'折旧科目代码',
                    'aliasName'=>'折旧科目代码',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',

                    'isMust'=>false,
                ],
            ]
        };
    }
}
